package cn.fotoit.product.system.service;

import cn.fotoit.product.system.entity.RoleRelPermission;
import cn.fotoit.product.system.repository.RoleRelPermissionRepository;
import cn.fotoit.product.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;


@Service
@CacheConfig(cacheNames = "queue_management_roleRelPermissionService")
@Transactional(readOnly = true)
public class RoleRelPermissionService {
    @Autowired
    private RoleRelPermissionRepository roleRelPermissionRepository;

    @CacheEvict(allEntries = true, cacheNames = {"queue_management_permissionService", "queue_management_roleRelPermissionService", "queue_management_roleService", "queue_management_userService"})
    @Transactional
    public void add(RoleRelPermission roleRelPermission) {
        roleRelPermissionRepository.save(roleRelPermission);
    }

    @CacheEvict(allEntries = true, cacheNames = {"queue_management_permissionService", "queue_management_roleRelPermissionService", "queue_management_roleService", "queue_management_userService"})
    @Transactional
    public void deleteById(Integer id) {
        roleRelPermissionRepository.deleteById(id);
    }

    @CacheEvict(allEntries = true, cacheNames = {"queue_management_permissionService", "queue_management_roleRelPermissionService", "queue_management_roleService", "queue_management_userService"})
    @Transactional
    public void updateNotNull(RoleRelPermission roleRelPermission) {
        Optional<RoleRelPermission> byId = roleRelPermissionRepository.findById(roleRelPermission.getId());
        if (byId.isPresent()) {
            RoleRelPermission obj = byId.get();
            BeanUtil.copyPropertiesIgnoreNull(roleRelPermission, obj);
            roleRelPermissionRepository.save(obj);
        }
    }


    @Cacheable(key = "'findById'+#id")
    public RoleRelPermission findById(Integer id) {
        Optional<RoleRelPermission> byId = roleRelPermissionRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    @Cacheable(key = "'findByRoleId'+#roleId")
    public List<RoleRelPermission> findByRoleId(Integer roleId) {
        return roleRelPermissionRepository.findByRoleId(roleId);

    }

    @Cacheable(key = "'findByPermissionId'+#permissionId")
    public List<RoleRelPermission> findByPermissionId(Integer permissionId) {
        return roleRelPermissionRepository.findByPermissionId(permissionId);
    }

}